<?php
/**
 * 语言常量
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/6/4 9:18
 * @copyright PanxSoft Inc.
 */

namespace App\Services\Locale;
use App\Models\Language;
use Illuminate\Support\Str;

class AppLanguage
{
    const LANG_DIR_EN = 'en';
    const LANG_DIR_ZH_HK = 'zh-HK';
    const LANG_DIR_ZH_CN = 'zh-CN';
    const DEFAULT_LOCALE = self::LANG_DIR_ZH_CN;

    public static function isCN($locale = null): bool
    {
        $locale = $locale ?: app()->getLocale();

        return Str::contains(strtolower($locale), ['cn', 'zh']);
    }

    /**
     * @param $lang
     */
    public static function setAppLocale(string $lang): void
    {
        if (config('pkx.force_locale')) {
            app()->setLocale(config('pkx.force_locale'));
            return;
        }

        app()->setLocale(self::normalizeLanguageCode($lang));
    }

    /**
     * @param $code
     * @return string
     */
    public static function normalizeLanguageCode($code)
    {
        $lower_str_code = mb_strtolower($code);

        if (Str::contains($lower_str_code, 'en')) {
            return self::LANG_DIR_EN;
        } else if (Str::contains($lower_str_code, ['hk', 'tw'])) {
            return self::LANG_DIR_ZH_HK;
        } else {
            return self::LANG_DIR_ZH_CN;
        }
    }

    /**
     * @example
     *      'zh-CN,zh;q=0.9,en;q=0.8,ja;q=0.7,fr;q=0.6,zh-TW;q=0.5'
     *   => 'zh-CN'
     *
     * @test
     *
     * @param string|null $header_lang
     *
     * @return array|string
     */
    public static function normalizeHeaderLanguage(string $header_lang = null): ?string
    {
        if (! $header_lang) {
            return null;
        }

        $locale_weight = head(explode(',', $header_lang));

        $locale_lang = head(explode(';', $locale_weight));

        return $locale_lang;
    }

    public static function headerFirstAcceptLanguage(): ?string
    {
        return self::normalizeLanguageCode(
            self::normalizeHeaderLanguage(
                request()->header('accept-language')
            )
        );
    }

    /**
     * Laravel 会找 resources/lang 下面对应文件夹名称对语言文件
     * 对于 zh_CN 等形式，会导致 app()->setLocale() 找不到对应的目录
     * 而变成 fallback 语言，setLocale 前必须把 zh_CN 转成 zh-cn 的形式
     *
     * @param string $language_code
     *
     * @return string
     */
    public static function normalizeLocale(string $language_code): string
    {
        return strtolower(Str::slug($language_code));
    }

    public static function getLanguageIdFromAppLocale()
    {
        $app_locale = app()->getLocale();

        return Language::memoFindByCode($app_locale)->id ?? Language::default()->id;
    }
}